package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * 用户下单
 *
 * @author 24040
 * @name OrderController
 * @date 2022-08-01 13:54
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    @CacheEvict(value = "orderCache" ,allEntries = true)
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据:{}", orders.toString());
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param ordersDto
     * @return
     */
    @GetMapping("/page")
    @Cacheable(value = "orderCache",
            key = "'orderPage_' + #page + '_' + #pageSize + '_' + #ordersDto.beginTime  + '_' + #ordersDto.endTime + '_' + #ordersDto.getId()",
            unless = "#result.getCode() == 0")
    public R<Page<Orders>> getPage(Integer page, Integer pageSize, OrdersDto ordersDto) {
        //log.info(ordersDto.toString());

        //构建分页查询构造器
        Page<Orders> ordersPage = new Page<Orders>(page, pageSize);
        //编写查询条件
        //select * from orders where (checkout_time BETWEEN ? and ? ) and number =  ?
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(ordersDto.getNumber() != null, Orders::getNumber, ordersDto.getNumber());
        queryWrapper.between(ordersDto.getBeginTime() != null && ordersDto.getEndTime() != null,
                Orders::getCheckoutTime, ordersDto.getBeginTime(), ordersDto.getEndTime());
        //进行分页出查询
        ordersPage = orderService.page(ordersPage, queryWrapper);
        return ordersPage != null ? R.success(ordersPage) : R.error("查询失败");
    }

    /**
     * 更新订单状态
     *
     * @param orders
     * @return 订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
     */
    @PutMapping
    @CacheEvict(value = "orderCache" ,allEntries = true)
    public R<String> order(@RequestBody Orders orders) {
        boolean b = orderService.updateById(orders);
        return b ? R.success("更新成功") : R.error("删除失败");
    }

    /**
     * 根据用户id 查询历史订单/最新订单
     * @param page
     * @param pageSize
     * @param session
     * @return
     */
    @GetMapping("/userPage")
    @Cacheable(value = "orderCache",
            key = "'userOrderPage_' + #page + '_' + #pageSize + #session.getAttribute('user')",
            unless = "#result.getCode() == 0")
    public R<Page<Orders>> userPage(Integer page, Integer pageSize, HttpSession session) {
        //取出当前用户id
        Long userId = Long.valueOf(session.getAttribute("user").toString());
        //构造分页查询器
        Page<Orders> ordersPage = new Page<Orders>(page, pageSize);
        //构造sql语句
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, userId);
        queryWrapper.orderByDesc(Orders::getCheckoutTime);
        //进行查询
        ordersPage = orderService.page(ordersPage, queryWrapper);
        return ordersPage != null ? R.success(ordersPage) : R.error("查询失败");
    }

    /**
     * 再来一单
     * @return
     */
    @PostMapping("/again")
    @CacheEvict(value = "orderCache" ,allEntries = true)
    public R<String> again(@RequestBody Orders orders, HttpSession session) {
        Long ordersId = orders.getId();
        Long userId = Long.valueOf(session.getAttribute("user").toString());
        boolean flag = orderService.again(ordersId, userId);
        if (!flag) {
            throw new CustomException("操作失败");
        }
        return R.success("操作成功");
    }
}
